import axios, { type InternalAxiosRequestConfig, type AxiosError, type AxiosRequestConfig } from "axios"
import { id } from "element-plus/es/locales.mjs";
interface AxiosRequestConfigEx extends AxiosRequestConfig {
    donNotShowLoading?: boolean
}

export type ResType<T = any> = {
    code: string;
    data: T;
    msg: string;
}

export type PageDataType<T> = {
    list: T[];
    pageNum: number;
    pageSize: number;
    total: number;
}

export type usersType = {
    avatar: string;
    deptId: number | null;
    email: string;
    gender: number | null;
    id: number;
    mobile: string;
    nickname: string;
    password: string;
    roleIds: number[];
    status: number;
    username: string;
}

export type tokenuserType = {
    userId: string,
    avatar: string,
    nickname: string,
    roles: string
}


const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_PATH,
    timeout: 2000
})


export const service = <T = any>(config: AxiosRequestConfigEx) => {
    return instance.request<ResType<T>>(config)
        .then(response => { return response.data })
}

instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    config.headers.set('Content-Type', 'application/json');
    config.headers.set('Authorization', localStorage.getItem('token'))
    return config
},
    (error: AxiosError) => {
        Promise.reject(error)
    })


instance.interceptors.response.use(
    response => {
        console.log('响应拦截器: ', response);
        return response;
    },
    error => {
        if (error.response.status === 401) {
            window.location.href = '/login';
        } else if (error.response.status === 500) {
            console.error('服务器错误');
        }
        return Promise.reject(error);
    }
);

export const addUser = (data: usersType) => {

    return service<PageDataType<usersType>>({
        method: 'post',
        url: '/users',
        headers: { Authorization: localStorage.getItem('token') },
        data
    })
}

export const getUser = (params: any) => {
    return service<PageDataType<usersType>>({
        method: 'get',
        url: '/users/page',
        params
    })
}

export const editUser = (userId: number, data: usersType) => {
    return service({
        method: 'put',
        url: `/users/${userId}`,
        data
    })
}

export const tokenuser = () => {
    return service<PageDataType<usersType>>({
        method: 'get',
        url: '/users/me',
        params: { Authorization: localStorage.getItem('token') }
    })
}

export const deluser = (ids: string) => {
    return service({
        method: 'delete',
        url: `/users/${ids}`,
    })
}

export const userInfo = (ids: number) => {
    return service({
        method: 'get',
        url: `/user/info/${ids}`,
        headers: { Authorization: localStorage.getItem('token') },
    })
}